import { EventEmitter } from "events";
import { useLayoutEffect } from "react";

const emitter = new EventEmitter();
window.eventBus2 = emitter;
let eventBus = {
    //订阅
    subscribe: function(eventName, listener){
        emitter.addListener(eventName, listener);
    },
    //销毁订阅
    unSubscribe: function(eventName, listener){
        emitter.removeListener(eventName, listener);
    },
    publish: function(eventName, data){
        emitter.emit(eventName, data);
    }
}

//全局创建订阅
function useOnEventBus(eventName, listener, depends = []){
    useLayoutEffect(function(){
        //订阅
        eventBus.subscribe(eventName, listener);

        return ()=>{
            //销毁
            eventBus.unSubscribe(eventName, listener);
        }
    }, depends)
}

//全局发送订阅
function publishEventBus(eventName, listener){
    eventBus.emit(eventName, listener);
}

//全局销毁订阅
function offEventBus(eventName, listener){
    eventBus.unSubscribe(eventName, listener);
}

export {
    useOnEventBus,
    publishEventBus,
    eventBus
}